package com.snsoft.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;

import com.snsoft.bean.User;
import com.snsoft.bean.UserInfo;
import com.snsoft.exception.BaseNotFound;
import com.snsoft.exception.DataIsNull;
import com.snsoft.exception.PromiseRefused;
import com.snsoft.exception.RepetOperate;
import com.snsoft.exception.UserExist;
import com.snsoft.service.duty.AddUserService;
import com.snsoft.service.duty.DeleteUserService;
import com.snsoft.service.duty.GetIndependentUserService;
import com.snsoft.service.duty.GetUsersService;
import com.snsoft.service.duty.SetOperateService;
import com.snsoft.util.Constants;
import com.snsoft.util.JsonUtils;

/**
 * 
 * @author 苏国启
 * 
 * @date 2017年11月6日 下午4:48:15
 * 
 * @Description TODO 超级管理员和基地负责人可以调用的接口
 *
 */
@WebServlet("/duty")
public class DutyController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DutyController() {
		super();
	}

	/**
	 * GET请求接口分流
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		if ("getIndependentUser".equals(method)) {
			this.getIndependentUser(request, response);
		} else {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
		}
	}

	/**
	 * POST请求接口分流
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("method");
		UserInfo admin = ((UserInfo) request.getSession(false).getAttribute("userInfo"));
		if ("addUser".equals(method)) {
			this.addUser(request, response, admin.getRole());
		} else if ("deleteUser".equals(method)) {
			this.deleteUser(request, response, admin);
		} else if ("resetPassword".equals(method)) {
			this.resetPassword(request, response);
		} else if ("getUsers".equals(method)) {
			this.getUsers(request, response, admin);
		} else if ("setGreenHouse".equals(method)) {
			this.setGreenHouse(request, response, admin);
		} else if ("setOperate".equals(method)) {
			this.setOperate(request, response, admin);
		} else {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请求异常！"));
		}

	}

	/**
	 * 获取独立用户列表接口
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void getIndependentUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			List<Map<String, Object>> data = new GetIndependentUserService().getIndependentUser();
			response.getWriter().write(JsonUtils.objectToJson(data, Constants.CODE_SUCCESS, Constants.JSON_SUCCESS));
			return;
		} catch (DataIsNull e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, e.getMessage()));
			return;
		} catch (Exception e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "系统出现错误，请及时联系管理员解决问题！"));
			return;
		}
	}

	/**
	 * 设置温室控制权限接口
	 * 
	 * @param request
	 * @param response
	 * @param admin
	 * @throws IOException
	 */
	private void setOperate(HttpServletRequest request, HttpServletResponse response, UserInfo admin)
			throws IOException {
		String userID = request.getParameter("userID");
		String operate = request.getParameter("operate");
		// 参数校验
		if (StringUtils.isBlank(userID) || !StringUtils.isNumeric(userID)) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "选择的用户ID错误！"));
			return;
		}
		if (StringUtils.isBlank(operate) || !operate.matches("[0|1]{1}")) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "设置的控制权限有错误！"));
			return;
		}
		try {
			new SetOperateService().setOperate(userID, operate, admin);
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_SUCCESS, Constants.JSON_SUCCESS));
			return;
		} catch (UserExist | PromiseRefused | RepetOperate e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, e.getMessage()));
			return;
		} catch (Exception e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "系统出现错误，请及时联系管理员解决问题！"));
			return;
		}
	}

	/**
	 * 分配温室权限接口
	 * 
	 * @param request
	 * @param response
	 * @param admin
	 */
	private void setGreenHouse(HttpServletRequest request, HttpServletResponse response, UserInfo admin) {
		// TODO Auto-generated method stub

	}

	/**
	 * 获取基地普通用户列表接口
	 * 
	 * @param request
	 * @param response
	 * @param admin
	 * @throws IOException
	 */
	private void getUsers(HttpServletRequest request, HttpServletResponse response, UserInfo admin) throws IOException {
		String companyID = request.getParameter("companyID");
		// 参数校验
		if (StringUtils.isBlank(companyID) || !StringUtils.isNumeric(companyID)) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "所查询的基地ID有误！"));
			return;
		}
		try {
			List<Map<String, Object>> data = new GetUsersService().getUsers(companyID, admin);
			response.getWriter().write(JsonUtils.objectToJson(data, Constants.CODE_SUCCESS, Constants.JSON_SUCCESS));
			return;
		} catch (PromiseRefused | BaseNotFound | DataIsNull e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, e.getMessage()));
			return;
		} catch (Exception e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "系统出现错误，请及时联系管理员解决问题！"));
			return;
		}
	}

	/**
	 * 重置密码接口，等确定用手机号注册后再写
	 * 
	 * @param request
	 * @param response
	 */
	@Deprecated
	private void resetPassword(HttpServletRequest request, HttpServletResponse response) {

	}

	/**
	 * 删除用户接口
	 * 
	 * @param request
	 * @param response
	 * @param admin
	 * @throws IOException
	 */
	private void deleteUser(HttpServletRequest request, HttpServletResponse response, UserInfo admin)
			throws IOException {
		String userID = request.getParameter("userID");
		// 参数校验
		if (StringUtils.isBlank(userID) || !StringUtils.isNumeric(userID)) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "请指定要删除的用户！"));
			return;
		}
		try {
			new DeleteUserService().deleteUser(userID, admin);
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_SUCCESS, Constants.JSON_SUCCESS));
		} catch (UserExist | PromiseRefused e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, e.getMessage()));
			return;
		} catch (Exception e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "系统出现错误，请及时联系管理员解决问题！"));
			return;
		}
	}

	/**
	 * 添加用户接口
	 * 
	 * @param request
	 * @param response
	 * @param operRole
	 * @throws IOException
	 */
	private void addUser(HttpServletRequest request, HttpServletResponse response, int operRole) throws IOException {
		User user = new User();
		String usercode = request.getParameter("userCode");
		String username = request.getParameter("userName");
		String role = request.getParameter("role");
		String operate = request.getParameter("operate");
		// 参数校验，添加了校验手机号，不需要可以删除
		if (StringUtils.isBlank(usercode) || !usercode.matches("1[3|4|5|7|8][0-9]{9}")) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "添加的帐号有误！"));
			return;
		}
		if (StringUtils.isBlank(username) || username.length() > 20) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "添加的用户名有误！"));
			return;
		}
		if (StringUtils.isBlank(role) || !role.matches("[0|2]{1}")) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "添加的用户身份有误！"));
			return;
		}
		if (StringUtils.isBlank(operate) || !operate.matches("[0|1]{1}")) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "用户的控制权限有误！"));
			return;
		}
		// 将添加的用户信息写入bean
		user.setUserCode(usercode);
		user.setUserName(username);
		user.setRole(Integer.parseInt(role));
		user.setOperate(Integer.parseInt(operate));
		try {
			Map<String, Object> data = new AddUserService().addUser(user, operRole);
			response.getWriter().write(JsonUtils.objectToJson(data, Constants.CODE_SUCCESS, "用户添加成功！"));
			return;
		} catch (UserExist | PromiseRefused | DataIsNull e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, e.getMessage()));
			return;
		} catch (Exception e) {
			response.getWriter().write(JsonUtils.objectToJson(null, Constants.CODE_ERROR, "系统出现错误，请及时联系管理员解决问题！"));
			return;
		}
	}
}
